import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/main/router'

NProgress.configure({
    showSpinner: false,//隐藏小圆圈动画
    speed: 300,//速度
    easing: 'ease'
})

const status = {
    isStart: false,//是否开启进度条
    routerCount: 0,//当前路由数量,有可能为负数,代表router没有通过beforeEach直接afterEach
    axiosCount: 0,//当前axios请求数量
    timeout: undefined,//记录隐藏进度条方法
    timeoutClearTime: 50//延迟隐藏进度条加载完成的时间
}

//开启进度条
const startNProgress = (from) => {
    if (status.timeout) {
        clearTimeout(status.timeout)
        status.timeout = undefined
    }
    if (from == 'router') status.routerCount++
    if (from == 'axios') status.axiosCount++
    if (!status.isStart) {
        NProgress.start()
        status.isStart = true
    }
    // console.log(from, 'start:', status.routerCount, status.axiosCount)
}
//完成进度条
const endNProgress = (from) => {
    if (status.timeout) clearTimeout(status.timeout)
    if (from == 'router') status.routerCount--
    if (from == 'axios') status.axiosCount--
    status.timeout = setTimeout(() => {
        if (status.routerCount <= 0 && status.axiosCount <= 0) {
            status.routerCount = 0
            status.axiosCount = 0
            status.isStart = false
            NProgress.done()
        }
        // console.log(from, 'end:', status.routerCount, status.axiosCount)
    }, status.timeoutClearTime)
}

//rooter设置nprogress
router.beforeEach((to, from, next) => {
    startNProgress('router')
    next()
});
router.afterEach(() => {
    endNProgress('router')
});

//axios设置nprogress
axios.interceptors.request.use(request => {
    startNProgress('axios')
    return request
}, error => {
    endNProgress('axios')
    return Promise.reject(error);
})
axios.interceptors.response.use(response => {
    endNProgress('axios')
    return response;
}, function (error) {
    endNProgress('axios')
    return Promise.reject(error);
});